package com.matt.foundation.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.matt.domain.ContractProduct;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import org.apache.commons.lang.RandomStringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.matt.foundation.constant.CommonConstant.SSO_CALL_ERROR_MSG;
import static com.matt.foundation.model.ErrorCode.JSON_STR_ERROR;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/7/11
 * *******************************
 */
public class ModelUtil {

    public static ObjectMapper objectMapper = new ObjectMapper();

    public static Integer getMonth(Long days) {
        return (int) (days / 30L + 1L);
    }

    public static Integer getDay(Long days) {
        return (int) (days % 30L + 1L);
    }


    public static String getCleanUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static String getSafeStr(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    public static Integer getNullInteger(Object obj) {
        return obj == null ? null : Integer.valueOf(obj.toString());
    }

    public static Integer getDefaultInteger(Object obj) {
        return obj == null ? 0 : Integer.valueOf(obj.toString());
    }


    public static String numToStr(Integer num) {
        if (num < 10)
            return "00" + num;
        if (num < 100)
            return "0" + num;
        else
            return "" + num;
    }

    public static String numToStrLenth2(Integer num) {
        if (num < 10)
            return "0" + num;
        else
            return "" + num;
    }


    public static String getAreaCityCode(String areaName) {
        if (areaName.startsWith("成都"))
            return "51";
        if (areaName.startsWith("上海"))
            return "31";
        if (areaName.startsWith("北京"))
            return "11";
        return "";
    }

    public static final String getRandomSerial(Integer length) {
        return RandomStringUtils.random(length, 48, 58, false, true);
    }

    public static final Integer matchLatelyMonth(Integer month) {
        if (month < 0)
            return 0;
        if (month < 7)
            return 7;
        if (month > 48)
            return 48;
        return month;
    }


    public static final Integer compute(Integer src, String formula){
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine se = manager.getEngineByName("js");
            String str = formula.replace("X", String.valueOf(src));
            Double result =(Double) se.eval(str);
            return (int) result.doubleValue();
        }catch (ScriptException e){
            e.printStackTrace();
        }
        return 0;
    }

    public static Map mapOf(List keys, List values){
        Map map =new HashMap();
        for (int i = 0 ; i<keys.size(); i++){
            if (Objects.isNull(keys.get(i)))
                throw new BusinessException(ErrorCode.UNDEFINED, "keys不能为空");

            if (Objects.isNull(values.get(i))){
                continue;
            }

            map.put(keys.get(i), values.get(i));
        }
        return map;
    }

    public static Map mapOf(Object key1, Object value1){
        Map map =new HashMap();
        map.put(key1, value1);
        return map;
    }

    public static Map mapOf(Object key1, Object value1, Object key2, Object value2){
        Map map =new HashMap();
        map.put(key1, value1);
        map.put(key2, value2);
        return map;
    }


    public static String toJson(Object o){
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.UNDEFINED, "json转换出错");
        }
    }

    public static <T> List<T> readListFormJson(String json, Class<T> clazz){
        try {
            JavaType javaType =ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
            return ModelUtil.objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.UNDEFINED, "json转换出错");
        }
    }

    public static int doubleToInt(double number) {
        BigDecimal bd = new BigDecimal(number).setScale(0, BigDecimal.ROUND_HALF_UP);
        return bd.intValue();
    }

    public static StatusResponse getResponse(String src, String errorMsg) {
        try {
            StatusResponse statusResponse = objectMapper.readValue(src, StatusResponse.class);
            if (statusResponse.getCode().equals(ErrorCode.UNDEFINED))
                throw new BusinessException(statusResponse.getCode(), errorMsg);
            if (!statusResponse.getCode().equals(ErrorCode.SUCCESSFUL))
                throw new BusinessException(statusResponse.getCode(), statusResponse.getMassage());
            return statusResponse;
        } catch (IOException e) {
            throw new BusinessException(JSON_STR_ERROR, errorMsg);
        }
    }

    public static double remainTwoPoint(double d){
        if (Objects.nonNull(d)){
            BigDecimal decimal = new BigDecimal(d);
            return decimal.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return 0d;
    }
}
